package cn.yangtianxia.org.controller;

import cn.yangtianxia.basic.annotation.PreAuthorize;
import cn.yangtianxia.basic.util.AjaxResult;
import cn.yangtianxia.basic.util.PageList;
import cn.yangtianxia.org.domain.Department;
import cn.yangtianxia.org.query.DepartmentQuery;
import cn.yangtianxia.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/dept")
@Api(value = "部门的API",description="部门相关的CRUD功能")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Department department){
        try {
            if(department.getId() != null){
                departmentService.update(department);
            }else{
                departmentService.save(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，稍后重试！！！");
        }
    }

    @DeleteMapping("/{id}")
    @PreAuthorize(name = "通过id删除一个对象", value = "department:removeById")
    public AjaxResult removeById(@PathVariable("id") Long id){
        try {
            departmentService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me() .setSuccess(false) .setMessage("系统繁忙，稍后重试！！！");
        }
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询" )
    public Department queryById(@PathVariable("id") Long id){
        return  departmentService.loadById(id);
    }


    @GetMapping
    public List<Department> queryAll(){
        return  departmentService.loadAll();
    }

    @PostMapping
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query){
        return  departmentService.queryPage(query);
    }

    @PatchMapping
    public AjaxResult batchRemove(@RequestBody List<Long> ids){
        try {
            departmentService.batchRemove(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me() .setSuccess(false) .setMessage("系统繁忙，稍后重试！！！");
        }
    }

    @GetMapping("/tree")
    public List<Department> queryTree(){
        return departmentService.queryTree();
    }
}